package com.magicsoft.share.ui.my;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.design.widget.TabLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.magicsoft.share.R;
import com.magicsoft.share.adapter.my.OrderCompletAdapter;
import com.magicsoft.share.adapter.my.OrderInCompletAdapter;
import com.magicsoft.share.base.BaseActivity;
import com.magicsoft.share.bean.my.OrderList;
import com.magicsoft.share.customview.alertview.AlertView;
import com.magicsoft.share.customview.alertview.OnItemClickListener;
import com.magicsoft.share.presenter.my.OrderPresenter;
import com.magicsoft.share.utils.DensityUtils;
import com.magicsoft.share.utils.ToastUtils;
import com.magicsoft.share.view.my.IOrderView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;
import com.yanzhenjie.recyclerview.swipe.widget.DefaultItemDecoration;

import java.lang.reflect.Field;

import butterknife.BindView;
import butterknife.OnClick;

public class OrderActivity extends BaseActivity<IOrderView, OrderPresenter> implements IOrderView {


    @BindView(R.id.view_top)
    View viewTop;
    @BindView(R.id.ibtn_left)
    ImageButton ibtnLeft;
    @BindView(R.id.tv_left)
    TextView tvLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.ibtn_right)
    ImageButton ibtnRight;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.tabLayout)
    TabLayout tabLayout;
    @BindView(R.id.recyclerView)
    SwipeMenuRecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    private OrderCompletAdapter orderCompletAdapter;
    private OrderInCompletAdapter orderInCompletAdapter;

    private int pageNum = 1;
    private int pageSize = 10;
    private int status = 1;//1 已完成 2未完成
    private boolean isRefresh = true;

    @Override
    public OrderPresenter initPresenter() {
        return new OrderPresenter();
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_order;
    }

    @Override
    public void initData() {

    }

    @Override
    public void initView() {
        tvTitle.setText("订单");

        setIndicator(this, tabLayout, 60, 60);
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int position = tab.getPosition();
                if (position == 0) {
                    //已完成
                    pageNum = 1;
                    status = 1;
                    isRefresh = true;
                    recyclerView.setAdapter(orderCompletAdapter);
                    requestData();

                } else {
                    pageNum = 1;
                    status = 2;
                    isRefresh = true;
                    recyclerView.setAdapter(orderInCompletAdapter);
                    requestData();

                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        initRV();

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                isRefresh = true;
                pageNum = 1;
                requestData();
            }
        });

    }

    @Override
    public void requestData() {
        mPresenter.orderList(status, pageNum, pageSize);

    }


    @OnClick(R.id.ibtn_left)
    public void onViewClicked() {
        finish();
    }


    private void initRV() {
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        recyclerView.addItemDecoration(new DefaultItemDecoration(getResources().getColor(R.color.bg2), 0, DensityUtils.dp2px(this, 20)));
        recyclerView.useDefaultLoadMore();
        recyclerView.loadMoreFinish(true, false);
        recyclerView.setLoadMoreListener(new SwipeMenuRecyclerView.LoadMoreListener() {
            @Override
            public void onLoadMore() {
                isRefresh = false;
                pageNum++;
                requestData();
            }
        });


        orderCompletAdapter = new OrderCompletAdapter(R.layout.item_order_complet);
        orderInCompletAdapter = new OrderInCompletAdapter(R.layout.item_order_incomplet);
        orderInCompletAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.btn_confirm) {
                    initDialog(position);

                } else if (view.getId() == R.id.btn_logistics) {
                    if(orderInCompletAdapter.getData().get(position).getStatus()==1){
                        ToastUtils.showToast(OrderActivity.this,"该商品暂未发货");
                    }else {
                        startActivity(new Intent(OrderActivity.this, LogisticsActivity.class)
                                .putExtra("carrier", orderInCompletAdapter.getData().get(position).getCarrier())
                                .putExtra("logisticsSingleNumber", orderInCompletAdapter.getData().get(position).getLogisticsSingleNumber())

                        );
                    }
                }
            }
        });


        recyclerView.setAdapter(orderCompletAdapter);

    }

    private void initDialog(final int position) {
        new AlertView.Builder().setTitle("确认收货？").
                setContext(this).setCancelText("取消").setOthers(new String[]{"确认"}).
                setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int mposition) {

                        if (mposition == 0) {

                            OrderList.ListBean item = orderInCompletAdapter.getItem(position);

                            mPresenter.confirmOrder(item.getOrderId());
                        }
                    }
                }).
                setStyle(AlertView.Style.Alert).
                build().
                show();
    }

    public void setIndicator(Context context, TabLayout tabs, float leftDip, float rightDip) {
        Class<?> tabLayout = tabs.getClass();
        Field tabStrip = null;//反射
        try {
            tabStrip = tabLayout.getDeclaredField("mTabStrip");
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

        tabStrip.setAccessible(true);
        LinearLayout ll_tab = null;
        try {
            ll_tab = (LinearLayout) tabStrip.get(tabs);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        int left = (int) (getDisplayMetrics(context).density * leftDip);
        int right = (int) (getDisplayMetrics(context).density * rightDip);

        for (int i = 0; i < ll_tab.getChildCount(); i++) {
            View child = ll_tab.getChildAt(i);
            child.setPadding(0, 0, 0, 0);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
            params.leftMargin = left;
            params.rightMargin = right;
            child.setLayoutParams(params);
            child.invalidate();
        }
    }

    public DisplayMetrics getDisplayMetrics(Context context) {
        DisplayMetrics metric = new DisplayMetrics();
        ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(metric);
        return metric;
    }

    @Override
    public void orderListSuccess(OrderList data) {
        if (status == 1) {
            if (isRefresh) {
                orderCompletAdapter.setNewData(data.getList());
            } else {
                orderCompletAdapter.addData(data.getList());
            }

            if (pageNum < data.getPages()) {
                recyclerView.loadMoreFinish(false, true);
            } else if (pageNum == data.getPages()) {
                recyclerView.loadMoreFinish(false, false);
            } else {
                recyclerView.loadMoreFinish(true, false);
            }
            refreshLayout.finishRefresh();

        } else {
            if (isRefresh) {
                orderInCompletAdapter.setNewData(data.getList());
            } else {
                orderInCompletAdapter.addData(data.getList());
            }

            if (pageNum < data.getPages()) {
                recyclerView.loadMoreFinish(false, true);
            } else if (pageNum == data.getPages()) {
                recyclerView.loadMoreFinish(false, false);
            } else {
                recyclerView.loadMoreFinish(true, false);
            }

            refreshLayout.finishRefresh();
        }

        if (orderInCompletAdapter.getData().size()>0) {
            Log.e("TAG", "隐藏背景"+orderInCompletAdapter.getData().size());
            recyclerView.setBackgroundColor(getResources().getColor(R.color.white));
        } else {
            recyclerView.setBackground(getResources().getDrawable(R.drawable.icon_nodata));
        }

        if (orderCompletAdapter.getData().size()>0) {

            recyclerView.setBackgroundColor(getResources().getColor(R.color.white));
        } else {
            recyclerView.setBackground(getResources().getDrawable(R.drawable.icon_nodata));
        }
    }

    @Override
    public void orderListFail() {
        refreshLayout.finishRefresh();
        if (isRefresh) {
            recyclerView.loadMoreFinish(true, false);
        } else {
            recyclerView.loadMoreFinish(false, false);
        }


    }

    @Override
    public void confirmOrderSuccess() {
        requestData();
    }


}
